package com.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by buguniao on 15/12/7.
 */
public class CharGen {
    public static void main(String[] args) throws IOException {
        byte[] rotation = getRotation();
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        ServerSocket serverSocket = serverSocketChannel.socket();

        InetSocketAddress address = new InetSocketAddress(8080);
        serverSocket.bind(address);
        serverSocketChannel.configureBlocking(false);

        Selector selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        while(true){
            selector.select();

            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> it = keys.iterator();
            while(it.hasNext()){
                SelectionKey key = it.next();
                try{
                    if(key.isAcceptable()){
                        ServerSocketChannel serverChannel = (ServerSocketChannel)key.channel();
                        SocketChannel socketChannel= serverChannel.accept();
                        socketChannel.configureBlocking(false);
                        SelectionKey key2 = socketChannel.register(selector, SelectionKey.OP_WRITE);
                        ByteBuffer bf = ByteBuffer.allocate(74);
                        bf.put(rotation,1,72).put((byte)'\r').put((byte)'\n');
                        bf.flip();
                        key2.attach(bf);
                        it.remove();
                    }else{
                        SocketChannel socketChannel = (SocketChannel)key.channel();
                        ByteBuffer bf = (ByteBuffer)key.attachment();
                        if(!bf.hasRemaining()){
                            bf.rewind();
                            byte first = bf.get();
                            bf.rewind();
                            bf.put(rotation,first-' '+1,72).put((byte)'\r').put((byte)'\n');
                            bf.flip();

                        }
                        socketChannel.write(bf);
                    }
                }catch (Exception e){
                    key.cancel();
                    key.channel().close();
                }

            }
        }
    }
    public static byte[] getRotation(){
        byte[] rotation = new byte[95*2];
        for(byte i=' ';i<='~';i++){
            rotation[i-' ']=i;
            rotation[i-' '+95]=i;
        }
        return rotation;
    }
}
